import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import type { IPermission } from "@/apis/acl/menu/type";
import {
  getAllPermissionApi,
  reqAddOrUpdateMenu,
  reqDeleteMenu,
} from "@/apis/acl/menu";
import { MsgEnum, AclEnum, curriedFn } from "../.";
import { listToTree, dateFormat, findParentId } from "@/utils/tools";

const msg = curriedFn(AclEnum.menu);

/**
 * 菜单权限仓库
 */
const usePermissionStore = defineStore("permissionStore", {
  state: (): {
    permissionList: IPermission[];
    // selectPermissions: IPermission[];
    loading: boolean;
  } => {
    return {
      permissionList: [],
      loading: false,
      // selectPermissions: [],
    };
  },
  actions: {
    async getPermissionList() {
      this.loading = true;
      try {
        const res = await getAllPermissionApi();
        if (res.code === 200) {
          this.permissionList = [...res.data];
          ElMessage(msg(MsgEnum.get));
          return "ok";
        }
      } catch (e: any) {
        ElMessage.error(e.message);
      } finally {
        this.loading = false;
      }
    },

    // async getMaryPermissionList(ids: string[] = []) {
    //   this.loading = true;
    //   try {
    //     const res = await getMaryPermissionApi(ids);
    //     if (res.code === 200) {
    //       this.selectPermissions = [...res.data];
    //       ElMessage(msg(MsgEnum.get));
    //     }
    //   } catch (e: any) {
    //     ElMessage.error(e.message);
    //   } finally {
    //     this.loading = false;
    //   }
    // },

    async addOrUpdatePermission(data: IPermission) {
      this.loading = true;
      try {
        const res = await reqAddOrUpdateMenu(data);
        if (res.code === 200) {
          this.getPermissionList();
          ElMessage.success(data._id ? msg(MsgEnum.update) : msg(MsgEnum.add));
        }
      } catch (e: any) {
        ElMessage.error(e.message);
      } finally {
        this.loading = false;
      }
    },

    async deletePermission(id: string) {
      this.loading = true;
      try {
        const res = await reqDeleteMenu(id);
        if (res.code === 200) {
          this.getPermissionList();
          ElMessage.success(msg(MsgEnum.delete));
        }
      } catch (e: any) {
        ElMessage.error(e.message);
      } finally {
        this.loading = false;
      }
    },
  },
  getters: {
    /**
     * 相当于计算属性；
     * 权限数据转换成树形结构，方便Tree展示
     * @param state 本参考属性状态
     * @returns 树形结构数组
     */
    permissionTree: state => {
      if (state.permissionList.length === 0) return [];
      const per = state.permissionList.map(item => {
        return {
          ...item,
          updatedAt: dateFormat(item.updatedAt as string),
          createdAt: dateFormat(item.createdAt as string),
        };
      });
      return listToTree(per, findParentId(per));
    },

    // menuCodeArr: state => state.selectPermissions.map(item => item.code),
  },
});

export default usePermissionStore;
